package com.zrrd.gmall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.gmall.model.product.*;
import com.zrrd.gmall.product.mapper.*;
import com.zrrd.gmall.product.service.SkuInfoService;
import com.zrrd.gmall.service.cache.GmallCache;
import com.zrrd.gmall.service.constant.RedisConst;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoMapper, SkuInfo> implements SkuInfoService {
    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private SkuImageMapper skuImageMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;
    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;
    @Override
    public List<SpuImage> getSpuImageList(Long spuId) {
        QueryWrapper<SpuImage> wrapper = new QueryWrapper<>();
        wrapper.eq("spu_id",spuId);
        List<SpuImage> spuImageList = spuImageMapper.selectList(wrapper);
        return spuImageList;
    }

    @Override

    public List<SpuSaleAttr> getSpuSaleAttrList(Long spuId) {
        return spuSaleAttrMapper.getSpuSaleAttrList(spuId);
    }

    @Override
    @Transactional
    public void saveSkuInfo(SkuInfo skuInfo) {
        //1.保存Sku基本信息
        this.save(skuInfo);
        //2.保存图片信息
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        for (SkuImage skuImage : skuImageList) {
            skuImage.setSkuId(skuInfo.getId());
            skuImageMapper.insert(skuImage);
        }
        //3.保存Sku选择的销售属性 sku_sale_attr_value
        List<SkuSaleAttrValue> saleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        for (SkuSaleAttrValue skuSaleAttrValue : saleAttrValueList) {
            skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            skuSaleAttrValue.setSkuId(skuInfo.getId());
            skuSaleAttrValueMapper.insert(skuSaleAttrValue);
        }
        //4.保存平台属性关系表
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        for (SkuAttrValue skuAttrValue : skuAttrValueList) {
            skuAttrValue.setSkuId(skuInfo.getId());
            skuAttrValueMapper.insert(skuAttrValue);
        }
    }

    @Override
    @GmallCache(prefix = "baseCategory:")
    public BaseCategoryView getBaseCategoryViewById(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    @Override
    @GmallCache(prefix = "skuPrice:")
    public BigDecimal getSkuPrice(Long skuId) {
        SkuInfo skuInfo = this.getById(skuId);
        if (skuInfo!=null){
            return skuInfo.getPrice();
        }
        return new BigDecimal("0");
    }
    //根据SkuId和spuId 查询出sku对应的spu 的销售属性以及属性值以及标记当前sku所选中的销售属性
    @Override
    @GmallCache(prefix = "spuSaleAttr:")
    public List<SpuSaleAttr> getSpuSaleAttrListBySkuId(Long skuId, Long spuId) {
        return spuSaleAttrMapper.getSpuSaleAttrListBySkuId(skuId,spuId);
    }
    //<!--    根据spu查出所有旗下的Sku属性值-->
    @Override
    public Map getSaleAttrValueBySku(Long spuId) {
        Map map = new HashMap<>();
        List<Map> saleAttrValueBySku = skuSaleAttrValueMapper.getSaleAttrValueBySku(spuId);
        for (Map m : saleAttrValueBySku) {
            map.put(m.get("value_ids"),m.get("sku_id"));
        }
        return map;
    }

    @Override
    @GmallCache(prefix = "skuInfo:")//一行等于一堆，参数是key的前缀
    public SkuInfo getSkuInfo(Long skuId) throws InterruptedException {
        //无论返回什么，都要给一个兜底的返回
        return this.getSkuInfoDB(skuId);
    }

    @Override
    public SkuInfo getSkuInfoDB(Long skuId) {
        //1.获取基本信息
        SkuInfo skuInfo = this.getById(skuId);
        QueryWrapper<SkuImage> wrapper = new QueryWrapper<>();
        wrapper.eq("sku_id",skuInfo.getId());
        List<SkuImage> skuImages = skuImageMapper.selectList(wrapper);
        skuInfo.setSkuImageList(skuImages);
        return skuInfo;
    }

    @Override
    @GmallCache(prefix = "category:")
    public List<JSONObject> getBaseCategoryList() {
        //创建最终返回的集合
        List<JSONObject> list =new ArrayList<>();
        //查询分类视图
        List<BaseCategoryView> categoryViews = baseCategoryViewMapper.selectList(null);
        
        //拆解再组装,按照1级分类id抽离出来 返回一个Map集合 key：1级分类 value 一行中的其他数据
        Map<Long, List<BaseCategoryView>> categoryMap = categoryViews.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
            
        //定义代表当前是第几条数据的变量
        int index = 1;
        //遍历map集合 -》获得一级分类下所有数据
        for (Map.Entry<Long, List<BaseCategoryView>> entry1 : categoryMap.entrySet()) {
            Long category1Id = entry1.getKey();
            //获取1级分类下所有数据的集合
            List<BaseCategoryView> category2List = entry1.getValue();


            //创建1级分类的对象
            JSONObject category1= new JSONObject();
            category1.put("index",index);
            category1.put("categoryId",category1Id);
            category1.put("categoryName",category2List.get(0).getCategory1Name());

            //变量自增
            index++;



            //获取二级分类的集合
            Map<Long, List<BaseCategoryView>> category2Map = category2List.stream().
                    collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            List<JSONObject> category2Child =new ArrayList<>();
            for (Map.Entry<Long, List<BaseCategoryView>> entry2 : category2Map.entrySet()) {
                Long category2Id = entry2.getKey();
                List<BaseCategoryView> category3List = entry2.getValue();
                //二级分类的json对象
                JSONObject category2= new JSONObject();
                category2.put("categoryId",category2Id);
                category2.put("categoryName",category3List.get(0).getCategory2Name());
                category2Child.add(category2);


                //三级分类
                List<JSONObject> category3Child = new ArrayList<>();
                for (BaseCategoryView baseCategoryView : category3List) {
                    //创建分类json对象
                    JSONObject category3= new JSONObject();
                    category3.put("categoryId",baseCategoryView.getCategory3Id());
                    category3.put("categoryName",baseCategoryView.getCategory3Name());
                    category3Child.add(category3);
                }
                //把c3的列表装入特定c2
                category2.put("categoryChild",category3Child);
            }
            //把c2的列表装入特定c1
            category1.put("categoryChild",category2Child);
            //将封装完毕c1加入json
            list.add(category1);
        }
        return list;
    }

    @Override
    public List<BaseAttrInfo> getBaseAttrInfo(Long skuId) {
        return baseAttrInfoMapper.getAttrListBySkuId(skuId);
    }


}
